package com.heima.exception;

import com.heima.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(Exception.class)
    public Result exceptionHandler(Exception e) {
        e.printStackTrace();
        return Result.error("产生系统错误");
    }

    @ExceptionHandler(DIYException.class)
    public Result exceptionHandler(DIYException e) {
        e.printStackTrace();
        return Result.error(e.getMessage());
    }

    // 处理数据库唯一键冲突异常（捕获实际抛出的DuplicateKeyException）
    @ExceptionHandler(DuplicateKeyException.class)
    public Result handleDuplicateKeyException(DuplicateKeyException e) {
        log.error("数据库唯一键冲突: {}", e.getMessage());
        String errorMsg = e.getMessage();

        // 使用正则表达式提取重复的值和约束名
        String duplicateValue = extractDuplicateValue(errorMsg);
        String fieldName = extractFieldName(errorMsg);

        if (duplicateValue != null && fieldName != null) {
            return Result.error(String.format("%s '%s' 已存在", fieldName, duplicateValue));
        }

        return Result.error("数据已存在");
    }

    // 提取重复的值（从单引号中获取）
    private String extractDuplicateValue(String errorMsg) {
        Pattern pattern = Pattern.compile("Duplicate entry '(.+?)' for key");
        Matcher matcher = pattern.matcher(errorMsg);
        return matcher.find() ? matcher.group(1) : null;
    }

    // 提取字段名（根据约束名映射）
    private String extractFieldName(String errorMsg) {
        if (errorMsg.contains("uk_user_phone")) {
            return "手机号";
        } else if (errorMsg.contains("uk_user_username")) {
            return "用户名";
        }
        return "数据";
    }
}
